package com.kerry.socket;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.timeout.ReadTimeoutException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kerry.mapper.UserMapper;
import com.kerry.model.User;

@Component
public class ServerUDPHandler extends ChannelInboundHandlerAdapter {
	
	@Autowired
	private UserMapper userMappper;

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ServerUDPHandler.class);

	public ServerUDPHandler() {
		
	}
	
	private void testset() throws Exception{
		Thread.sleep(2000);
		List<User> list = userMappper.getAll();
		System.out.println("list size:"+list.size());
		for (User u:list) {
			System.out.println(u.toString());
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		DatagramPacket dpaket = (DatagramPacket) msg;
		// 这里是协议解析逻辑部分，这部分商业原因 不公开了 注意的是dpaker.sender()是来源地址因为udp是无连接的
		// 所以ctx.channel().remoteAddresss 都是空 null 所以需要使用dpaker.sender()
		// 在TCP里面可以ctx.channel。xxxh
		System.out.println("读数据开始");
		ByteBuf bbBuf = dpaket.content();
		
		byte[] byfs = new byte[bbBuf.readableBytes()];
		bbBuf.readBytes(byfs);
		
		System.out.println(new String(byfs));
		
		testset();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		if (cause instanceof ReadTimeoutException) {
			// eventChatLauncher.sendTimeout(); //全局超时
		} else {
			ctx.channel().close();
			// super.exceptionCaught(ctx, cause);
		}
	}

}
